/**
 * 限额穿透报表组件
 * 入参：onRef 父组件调用组件里的方法 默认onRef:()=>{}
 type: 1-主功能页面调用  2-穿透工作台调用
 组件内部增加设置查询事件如下：

 settingAndSearch：type=2时父组件通过onRef调用settingAndSearch({productCode产品,date查询日期})方法，并传递产品code和查询日期,该函数对组件内的产品和查询日期赋值，并调用组件内部查询事件
 该方法需要比对当前查询条件和传递过来的参数是否一致，如果一致将不做处理，不一致则重新查询
 */
import accounting from 'accounting';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { connect } from 'dva';
import uuid from 'es6-uuid';
import _ from 'lodash';
import moment from 'moment';
import React, { PureComponent } from 'react';

import myStyle from './index.less';
import MyModal from './myModal';

import { DATA_ENTRY, AdvancedSearch, ModalC, TableC, PrimaryC, InfoTipsC } from '@/comps/index';
import { findTitleByValue, getColumnIntoWidth } from '../../../utils/utils';

const statisticsType = [
  { value: 'ZCGLJH', title: '资产管理计划' },
  { value: 'WW', title: '委外投资' },
  { value: 'SMJJ', title: '私募基金' },
];
const isBooleanArr = [
  { value: '0', title: '是' },
  { value: '1', title: '否' },
];
function showValueForNewEnum(key, dictMap, value) {
  const values = dictMap[key];
  if (!values) return '';
  let text = '';
  values.forEach((item) => {
    if (item.code == value) text = item.value;
  });
  return text;
}
@Form.create()
@connect(({ limitThroughReportNewM, loading, globalM }) => ({
  limitThroughReportNewM,
  tableLoading: loading.effects['limitThroughReportNewM/getTableData'],
  loading,
  globalM,
}))
export default class limitThroughC extends PureComponent {
  static defaultProps = {
    onRef: () => {},
  };

  state = {
    dataSource: [],
    columns: [],
    visible: false, // 模态框显示与否
    searchForm: { isPassThrough: '1' }, // 搜索条件
    productCodeList: [],
    isReset: false, // 是否重置
    previewDate: undefined,
    isShowLog: false, // 数据日志弹窗是否显示
    logData: {}, // 数据日志数据
    logColumns: [
      { key: 'expirationDate', title: '报表日期' },
      { key: 'tradeType', title: '资产类型' },
      { key: 'tradingCode', title: '证券代码' },
      { key: 'tradingName', title: '证券全称' },
      { key: 'isValuation', title: '是否提供当日估值解析' },
      { key: 'valuationDate', title: '最新估值表数据日期' },
    ],
  };

  componentDidMount() {
    // 查询 T-1 日期
    this.getPreviousData();
    this.props.onRef(this);
  }

  // 查询T-1 交易日
  getPreviousData = () => {
    this.props.dispatch({
      type: 'limitThroughReportNewM/getPreviewDay',
      payload: {
        date: moment().format('YYYY-MM-DD'),
        tenant: localStorage.getItem('antd-pro-tenant'),
      },
      callback: (msg, date) => {
        if (msg == 'success') {
          this.setState(
            {
              previewDate: moment(date).format('YYYY-MM-DD'),
            },
            () => {
              this.queryTableList();
              // 截止时间赋初值
              this.searchRef?.props.form.setFieldsValue({
                date: moment(date),
              });
            },
          );
        }
      },
    });
  };

  // 展示表格
  showTable = () => {
    const { columns = [], dataSource = [] } = this.state;
    const {
      tableLoading,
      globalM: { dataDictionary: dictMap },
    } = this.props;
    const newColumns = _.cloneDeep(columns); // 自动计算width并插入
    if (newColumns?.length) {
      newColumns.map((item) => {
        if (item.key == 'riskLevel') {
          item.render = (val) => <span>{val !== null ? showValueForNewEnum('riskLevel', dictMap, val) : '--'}</span>;
        }
        if (item.key == 'riskCategory') {
          item.render = (val) => <span>{val !== null ? showValueForNewEnum('riskCategory', dictMap, val) : '--'}</span>;
        }
        if (item.key == 'ruleNo') item.width = 90;
        if (item.key != 'ruleNo' && item.key != 'ruleDesc' && item.key != 'operate') {
          item.align = 'left';
          item.width = 80;
          if (['detailValue', 'marginValue', 'prohibitValue', 'warningValue'].includes(item.key)) {
            item.width = 150;
            if (['prohibitValue', 'warningValue'].includes(item.key)) item.width = 80;
            item.render = (text, record) => {
              if (record.pecentView === false) {
                return text !== null ? accounting.formatNumber(Number(text), 2) : '--';
              }
              return text !== null ? `${accounting.formatNumber(Number(text) * 100, 2)}%` : '--';
            };
          }
        }
        // 监管法规render处理
        if (item.key == 'ordinance') {
          item.width = 160;
          item.render = (val) => <span>{val !== null ? showValueForNewEnum('riskOrdinance', dictMap, val) : '--'}</span>;
        }
        if (item.key == 'ruleDesc') {
          if (this.props.type == '1') {
            item.ellipsis = true; // 如果需要一列自适应宽度 其他列需要固定宽度，否则大屏幕的时候 所有列等比加宽
          } else {
            item.type = 'maxContent';
            item.width = 450; // 在穿透工作台的时候设置最大宽度 超过则省略
          }
        }
      });
      newColumns.push({
        title: '操作',
        key: 'operate',
        width: 60,
        fixed: this.props.type == 2 ? 'right' : undefined,
        render: (text, record) => <a onClick={() => this.showInfo(record)}>详细 </a>,
      });
    }
    const screenWidth = document.documentElement.clientWidth; // 获取屏幕宽度
    let width = 1500;
    if (screenWidth < 1600) {
      width = 1500;
    } else if (screenWidth > 1600 && screenWidth < 1921) {
      width = 1500;
    } else if (screenWidth > 1921) {
      width = 1600;
    }
    return (
      <div style={{ marginTop: '15px' }}>
        <TableC
          loading={tableLoading}
          columns={newColumns}
          dataSource={dataSource}
          hidePage={true}
          selfScrollY={true}
          scroll={this.props.type == 2 ? { x: 'max-content', y: 378 } : { x: width }}
          rowKey='rowId'
        />
      </div>
    );
  };

  // 查询详情页信息 弹出模态框
  showInfo = (record) => {
    record.date = moment(this.state.searchForm?.date || this.state.previewDate).format('YYYY-MM-DD');
    record.isPassThrough = this.searchRef?.props.form.getFieldValue('isPassThrough');
    this.setState({
      visible: true,
      rowRecord: record,
      timeStamp: new Date().getTime(),
    });
  };

  // 模态框
  showModal = () => {
    const { rowRecord, visible, timeStamp } = this.state;
    const props = {
      visible,
      onOk: () => {
        this.setState({ visible: false });
      },
      onCancel: () => {
        this.setState({ visible: false });
      },
      title: '限额详情',
      className: 'limitDetail',
      footer: null,
      height: 500,
      maskClosable: false, // 点击蒙层不可以关闭
    };
    return (
      <div>
        <ModalC {...props}>
          <MyModal record={rowRecord} timeStamp={timeStamp} type='report' />
        </ModalC>
      </div>
    );
  };

  // 点击查询
  onQuery = (params) => {
    const { productCodeList } = this.state;
    if (params.date) {
      params.date = params.date.format('YYYY-MM-DD');
    }
    if (params?.productCodeList?.length) {
      params.productCodeList = productCodeList;
    }
    this.setState(
      {
        isReset: false,
        currentPage: 1,
        searchForm: {
          ...params,
          riskLevel: params.riskLevel ? Number(params.riskLevel) : undefined, // 风险等级 int
        },
      },
      () => {
        this.queryTableList();
      },
    );
  };

  // 点击重置
  onClear = () => {
    this.setState({
      isReset: true,
      productCodeList: [],
    });
    if (this.state.previewDate) {
      this.searchRef?.props.form.setFieldsValue({
        date: moment(this.state.previewDate),
      });
    }
  };

  // 选中产品
  productOnChange = (e) => {
    // 取产品的code 传给后台
    if (!e) {
      this.setState({
        productCodeList: [],
      });
      return;
    }
    const arr = e?.info?.map((item) => item?.portfolioCode) || [];
    this.setState({
      productCodeList: arr || [],
    });
  };

  // 展示数据日志弹窗
  showLog = () => {
    this.queryLogList(); // 查询数据日志
    this.setState({
      isShowLog: true,
    });
  };

  // 查询日志列表
  queryLogList = () => {
    this.props.dispatch({
      type: 'limitThroughReportNewM/queryLogList',
      payload: {
        expirationDate: moment(this.state.searchForm?.date || this.state.previewDate).format('YYYY-MM-DD'),
      },
      callback: (data) => {
        if (data) {
          data?.dataSource?.map((item) => {
            item.id = uuid(16);
          });
        }
        this.setState({
          logData: data || {},
        });
      },
    });
  };

  // 展示数据日志弹窗
  showModalLog = () => {
    const { isShowLog, logData, searchForm } = this.state;
    const props = {
      visible: isShowLog,
      onOk: () => {
        this.setState({ isShowLog: false });
      },
      onCancel: () => {
        this.setState({ isShowLog: false });
      },
      title: '数据日志',
      footer: null,
      height: 500,
      width: 900,
      maskClosable: false,
    };
    const date = searchForm.date ? moment(searchForm.date) : this.searchRef.props.form.getFieldValue('date');
    return (
      <div>
        <ModalC {...props}>
          <div>
            <div>
              跑批结束时间：
              {logData.runEndDateTime ? moment(logData.runEndDateTime).format('YYYY-MM-DD HH:mm:ss') : '--'}
            </div>
            {logData.statistics &&
              logData.statistics.map((item, key) => (
                // eslint-disable-next-line react/no-array-index-key
                <div key={key} style={{ lineHeight: '24px' }}>
                  {date?.format('YYYY-MM-DD')}
                  日存续
                  {findTitleByValue(item.type, statisticsType)}共{item.count || 0}
                  只，当日估值解析已导入
                  {item.successCount || 0}
                  只，尚未导入
                  {item.failCount || 0}
                  只。
                </div>
              ))}
            {this.showLogTable()}
          </div>
        </ModalC>
      </div>
    );
  };

  // 通过产品id 获取到产品code
  getProductCodesById = (data = []) => {
    const arr = [];
    if (data.length) {
      this.ProductRef.state.dataSource.map((item) => {
        data.map((x) => {
          if (x == item.value) {
            arr.push(item.portfolioCode);
          }
        });
      });
    }
    return arr;
  };

  // 设置查询条件并查询列表
  settingAndSearch = (obj) => {
    const { searchForm } = this.state;
    const {
      form: { setFieldsValue },
    } = this.searchRef.props;
    console.log(obj);
    obj.productCodeList = this.getProductCodesById(obj.productIds);
    // 如果查询条件相同 则不做处理
    if (JSON.stringify(obj.productCodeList) == JSON.stringify(searchForm.productCodeList) && obj.date == searchForm.date) return;

    setFieldsValue({
      productCodeList: obj.productIds?.length ? obj.productIds : undefined,
      date: moment(obj.date),
    });
    if (obj.productCodeList?.length) searchForm.productCodeList = obj.productCodeList;
    else delete searchForm.productCodeList;
    searchForm.date = obj.date;
    this.setState(
      {
        searchForm: { ...searchForm },
        productCodeList: obj.productCodeList || undefined,
      },
      () => {
        this.queryTableList();
      },
    );
  };

  // 查询表格数据
  queryTableList = () => {
    const { searchForm, previewDate } = this.state;
    const { dispatch } = this.props;
    searchForm.riskCheckMode = searchForm.isPassThrough == '1' ? 'DAYEND_SPLIT' : 'DAYEND_NO_SPLIT';
    delete searchForm.isPassThrough;
    dispatch({
      type: 'limitThroughReportNewM/getTableData',
      payload: {
        // currentPage: 1,
        // numInPage: 999,
        date: previewDate,
        ...searchForm,
      },
      callback: (msg, _data) => {
        if (msg == 'success') {
          _data?.dataSource.map((item) => (item.rowId = uuid(16)));
          this.setState({
            dataSource: _data?.dataSource || [],
            columns: _data?.columns || [],
          });
        } else {
          this.setState({
            dataSource: [],
            columns: _data?.columns || [],
          });
        }
      },
    });
  };

  // 数据日志表格
  showLogTable = () => {
    const { loading } = this.props;
    const { logColumns = [], logData } = this.state;
    logColumns.map((item) => {
      if (item.key == 'tradeType') {
        item.render = (text) => findTitleByValue(text, statisticsType);
      }
      if (item.key == 'isValuation') {
        item.render = (text) => findTitleByValue(text, isBooleanArr);
      }
      if (item.key == 'expirationDate') {
        item.type = 'date';
      }
    });
    return (
      <div style={{ marginTop: '20px' }}>
        <TableC
          loading={loading.effects['limitThroughReportNewM/queryLogList'] == true}
          columns={logColumns}
          dataSource={logData.dataSource || []}
          hidePage={true}
          scroll={{ y: 300 }}
          rowKey='id'
        />
      </div>
    );
  };

  render() {
    const {
      globalM: { dataDictionary: dictMap },
      type,
      parentId,
    } = this.props;
    // 监管法规dataSource
    function mapEnum(arr) {
      const temp = [];
      if (!arr) return temp;
      arr.map((item) => {
        temp.push({
          title: item.value,
          value: item.code,
        });
      });
      return temp;
    }
    // 监管法规dataSource
    const regulationsArr = dictMap.riskOrdinance ? mapEnum(dictMap.riskOrdinance) : [];
    const riskLevelArr = dictMap.riskLevel ? mapEnum(dictMap.riskLevel) : [];
    const riskCategoryArr = dictMap.riskCategory ? mapEnum(dictMap.riskCategory) : [];
    const searchProps = {
      parentId,
      dataSource: [
        {
          dataIndex: 'date',
          title: type == 1 ? '截止日期' : '查询日期',
          type: DATA_ENTRY.SINGLEDATE,
          allowClear: false,
          disableEnd: this.state.previewDate ? moment(this.state.previewDate).add(1, 'days') : undefined,
        },
        {
          dataIndex: 'isPassThrough',
          title: '是否穿透',
          type: DATA_ENTRY.SELECT,
          isTrueFalseJudge: true,
          initialValue: '1',
        },
        {
          dataIndex: 'productCodeList',
          title: type == 1 ? '产品' : '产品名称',
          type: DATA_ENTRY.PRODUCTLIST,
          multiple: true,
          onChange: this.productOnChange,
          onRef: (e) => {
            this.ProductRef = e;
          },
        },
        {
          dataIndex: 'riskCategory',
          title: '风险类型',
          type: DATA_ENTRY.SELECT,
          dataSource: riskCategoryArr,
          allowClear: true,
          isMultiple: true,
        },
        {
          dataIndex: 'riskLevel',
          title: '风险等级',
          type: DATA_ENTRY.SELECT,
          dataSource: riskLevelArr,
          allowClear: true,
        },
        {
          dataIndex: 'ordinance',
          title: '监管法规',
          type: DATA_ENTRY.SELECT,
          dataSource: regulationsArr,
          allowClear: true,
        },
      ],
      onQuery: this.onQuery,
      onClear: this.onClear,
      onRef: (ref) => (this.searchRef = ref),
    };
    return (
      <div className={myStyle.LimitReport}>
        <AdvancedSearch {...searchProps} />
        {type == 1 ? <PrimaryC title='数据日志' disabled={this.state.dataSource?.length == false} onClick={this.showLog} style={{ marginTop: '15px' }} /> : null}
        {type == 2 ? (
          <div style={{ marginTop: '15px' }} className={myStyle.info}>
            <InfoTipsC style={{ paddingLeft: '20px', width: '100%', height: '32px' }} Left='默认展示跨产品所有限额条目；每日下午6点后可查询前一交易日穿透结果。' />
          </div>
        ) : null}
        {this.showTable()}
        {this.state.visible && this.showModal()}
        {this.state.isShowLog && this.showModalLog()}
      </div>
    );
  }
}
